package com.zlf.gulimall.product.exption;

import com.zlf.common.exception.BizCodeEnum;
import com.zlf.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ：张利锋
 * @date ：Created in 2020/12/10 20:50
 * @description： TOOD
 * @version: 1.0
 */
@Slf4j
@RestControllerAdvice("com.zlf.gulimall.product.controller")
public class ProductExceptionAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e){
      log.info(e.getMessage(),e.getClass());
        BindingResult result = e.getBindingResult();
        Map<String, String> map=new HashMap<>();
            result.getFieldErrors().forEach(item->{
                String message = item.getDefaultMessage();
                String field = item.getField();
                map.put(field,message);
            });
            return R.error(BizCodeEnum.VAILD_EXCEPTION.getCode(),BizCodeEnum.VAILD_EXCEPTION.getMessage()).put("data",map);
    }

    @ExceptionHandler(value = Exception.class)
    public R handlerException(Exception e){
        return R.error(BizCodeEnum.UNKNOWN_EXCEPTION.getCode(),BizCodeEnum.UNKNOWN_EXCEPTION.getMessage());
    }
}
